/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sv.com.intesal.others.controlador;

import java.sql.ResultSet;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import sv.com.intesal.clases.abstracts.ControladorAbstract;
import sv.com.intesal.clases.auxiliar.RutaProyecto;
import sv.com.intesal.others.bean.Login;
import sv.com.intesal.others.bean.PersonSession;
import sv.com.intesal.others.sql.SQLLogin;

/**
 *
 * @author ejerez
 */
public class LoginControlador extends ControladorAbstract {

    public Boolean validarLogin(Login l) throws Exception {
        try {
            super.setPreparedStatement(SQLLogin.getUsuario_x_Credenciales);
            super.ps.setString(1, l.getUser_l());
            super.ps.setString(2, l.getPassword_l());
            super.getExecuteQuery(super.ps);

            while (super.rs.next()) {
                this.crearSessionLoginUsuario(super.rs);
                this.redireccionPaginaPrincipal();
                return true;
            }
            return false;
        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            super.setCloseConexion();
        }
    }

    private void crearSessionLoginUsuario(ResultSet rs) throws Exception {
        try {

            FacesContext context = FacesContext.getCurrentInstance();
            HttpSession session = (HttpSession) context.getExternalContext().getSession(true);

            PersonSession person = (PersonSession) session.getAttribute("personSession");

            if (person == null) {
                person = new PersonSession();
            }

            /*EMPLEADO*/
            person.setNombre_e(rs.getString("nombre_e"));
            person.setApellido_e(rs.getString("apellido_e"));
            person.setNombre_completo_e(rs.getString("nombre_e") + " " + rs.getString("apellido_e"));

            /*USUARIO*/
            person.setCodigo_u(rs.getInt("codigo_u"));
            person.setNombre_u(rs.getString("nombre_u"));

            /*Crear session personSession*/
            session.setAttribute("personSession", person);
        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            super.setCloseConexion();
        }
    }

    private void redireccionPaginaPrincipal() throws Exception {
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            context.getExternalContext().redirect(RutaProyecto.wfrmPrincipal);
        } catch (Exception e) {
            throw new Exception(e);
        }
    }
}
